package com.example.searchservice.service.impl;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.*;
import co.elastic.clients.elasticsearch.core.search.Hit;
import com.example.searchservice.doc.StudentDocument;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class StudentServiceImpl {

    private static final String INDEX_NAME = "users";

    @Autowired
    private ElasticsearchClient elasticsearchClient;

    // 创建或更新用户
    public String createOrUpdateStudent(StudentDocument student) throws IOException {
        IndexResponse response = elasticsearchClient.index(i -> i
                .index(INDEX_NAME)
                .id(student.getId())
                .document(student)
        );
        return response.id();
    }

    // 根据ID获取用户
    public StudentDocument getStudentById(String id) throws IOException {
        GetResponse<StudentDocument> response = elasticsearchClient.get(g -> g
                        .index(INDEX_NAME)
                        .id(id),
                StudentDocument.class
        );

        if (response.found()) {
            return response.source();
        } else {
            return null;
        }
    }

    // 搜索用户
    public List<StudentDocument> searchStudents(String searchTerm) throws IOException {
        SearchResponse<StudentDocument> response = elasticsearchClient.search(s -> s
                        .index(INDEX_NAME)
                        .query(q -> q
                                .multiMatch(m -> m
                                        .query(searchTerm)
                                        .fields("name", "email", "city")
                                )
                        ),
                StudentDocument.class
        );

        return response.hits().hits().stream()
                .map(Hit::source)
                .collect(Collectors.toList());
    }

    // 根据名称搜索用户
    public List<StudentDocument> searchByName(String name) throws IOException {
        SearchResponse<StudentDocument> response = elasticsearchClient.search(s -> s
                        .index(INDEX_NAME)
                        .query(q -> q
                                .match(m -> m
                                        .field("name")
                                        .query(name)
                                )
                        ),
                StudentDocument.class
        );

        return response.hits().hits().stream()
                .map(Hit::source)
                .collect(Collectors.toList());
    }

    // 删除用户
    public boolean deleteStudent(String id) throws IOException {
        DeleteResponse response = elasticsearchClient.delete(d -> d
                .index(INDEX_NAME)
                .id(id)
        );

        return response.result().name().equals("Deleted");
    }

    // 获取所有用户
    public List<StudentDocument> getAllStudents() throws IOException {
        SearchResponse<StudentDocument> response = elasticsearchClient.search(s -> s
                        .index(INDEX_NAME)
                        .query(q -> q.matchAll(m -> m)),
                StudentDocument.class
        );

        return response.hits().hits().stream()
                .map(Hit::source)
                .collect(Collectors.toList());
    }

    // 检查索引是否存在
    public boolean indexExists() throws IOException {
        return elasticsearchClient.indices().exists(e -> e.index(INDEX_NAME)).value();
    }

    // 创建索引
    public boolean createIndex() throws IOException {
        elasticsearchClient.indices().create(c -> c.index(INDEX_NAME));
        return true;
    }
}